package org.dromara.kitchen.controller;

import java.util.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.mybatis.core.page.PageUtils;
import org.dromara.kitchen.domain.kitchen.KitchenFood;
import org.dromara.kitchen.domain.kitchen.KitchenSetMeal;
import org.dromara.kitchen.domain.kitchen.KitchenSetMealFoodType;
import org.dromara.kitchen.domain.kitchen.KitchenSetMealInfo;
import org.dromara.kitchen.domain.product.ProductImg;
import org.dromara.kitchen.domain.vo.KitchenFoodVO;
import org.dromara.kitchen.service.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 套餐
 *
 * @author Mr.Zhou
 * @date 2024-12-04
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/kitchen/setMeal")
public class KitchenSetMealController extends BaseController {

    private final IKitchenSetMealService kitchenSetMealService;
    private final IKitchenSetMealImgService kitchenSetMealImgService;
    private final IKitchenSetMealInfoService kitchenSetMealInfoService;
    private final IKitchenFoodService foodService;
    private final IBdProvinceService bdProvinceService;

    /**
     * 查询套餐列表
     */
    @SaCheckPermission("kitchen:setMeal:list")
    @GetMapping("/list")
    public TableDataInfo<KitchenSetMeal> list(KitchenSetMeal kitchenSetMeal, PageQuery pageQuery) {
        QueryWrapper<KitchenSetMeal> qw = new QueryWrapper<>();

        TableDataInfo<KitchenSetMeal> td = PageUtils.buildDataInfo(kitchenSetMealService.page(PageUtils.buildPage(),qw));
        List<KitchenSetMeal> list = td.getRows();
        for (KitchenSetMeal setMeal : list){
            setMeal.setAreaName(bdProvinceService.getAreaNameByAreaId(setMeal.getProvId(), setMeal.getCityId(), setMeal.getDistrictId()));
        }
        return td;
    }

    /**
     * 导出套餐列表
     */
    @SaCheckPermission("kitchen:setMeal:export")
    @Log(title = "套餐", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(KitchenSetMeal kitchenSetMeal, HttpServletResponse response) {
        List<KitchenSetMeal> list = kitchenSetMealService.list();
        ExcelUtil.exportExcel(list, "套餐", KitchenSetMeal.class, response);
    }

    /**
     * 获取套餐详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("kitchen:setMeal:query")
    @GetMapping("/{id}")
    public R<KitchenSetMeal> getInfo(@NotNull(message = "主键不能为空") @PathVariable Integer id) {
        KitchenSetMeal meal = kitchenSetMealService.getById(id);
        if(meal != null){
            if(meal.getProvId()!= null){
                String[] areas = { meal.getProvId() + "", meal.getCityId() + "", meal.getDistrictId() + "" };
                meal.setProvinceArray(areas);
            }

        }
        return R.ok(meal);
    }

    /**
     * 查询规格和商家服务类型列表
     */
    @GetMapping("/getSetMealInfoTransferData")
    public R<Map<String,Object>> getTransferData(@Validated KitchenSetMealFoodType foodType) {
        Map<String, Object> map = new HashMap<>();
        List<KitchenFoodVO> foodChooseList = new ArrayList<>();
        List<Integer> foodIdList = new ArrayList<>();
        QueryWrapper<KitchenSetMealInfo> qw = new QueryWrapper<>();
        qw.eq("meal_id", foodType.getMealId());
        qw.eq("food_type_id", foodType.getFoodTypeId());
        qw.eq("state", 1);
        List<KitchenSetMealInfo> infos = kitchenSetMealInfoService.list(qw);
        if(CollUtil.isNotEmpty(infos)){
            for (KitchenSetMealInfo mealInfo : infos){
                KitchenFoodVO foodVO = new KitchenFoodVO();
                foodVO.setFoodId(mealInfo.getFoodId());
                KitchenFood food = foodService.getById(mealInfo.getFoodId());
                if(food != null){
                    foodVO.setFoodTypeName(food.getFoodTypeName());
                    foodVO.setPrice(food.getPrice());
                    foodVO.setCount(food.getCount());
                    foodVO.setWeight(food.getWeight());
                    foodVO.setUnit(food.getUnit());
                    foodVO.setImgUrl(food.getImgUrl());
                    foodVO.setOrigin(food.getOrigin());
                }
                foodVO.setFoodName(mealInfo.getFoodName());
                foodVO.setLabelFoodName(mealInfo.getFoodName() + " - " + food.getFoodTypeName() + '￥'+ food.getPrice());
                foodChooseList.add(foodVO);
                foodIdList.add(mealInfo.getFoodId());
            }
        }
        map.put("foodIdList", foodIdList);
        map.put("foodChooseList", foodChooseList);
        map.put("mealInfoList", infos);

        List<KitchenFoodVO> foodAllList = new ArrayList<>();
        QueryWrapper<KitchenFood> qwFood = new QueryWrapper<>();
        if(foodType.getFoodTypeId() != null){
            qwFood.eq("food_type_id", foodType.getFoodTypeId());
        }
        qwFood.eq("state", 1);
        List<KitchenFood> foods = foodService.list(qwFood);
        if(CollUtil.isNotEmpty(foods)){
            for(KitchenFood food : foods){
                KitchenFoodVO foodVO = new KitchenFoodVO();
                foodVO.setFoodId(food.getId());
                foodVO.setLabelFoodName(food.getFoodName()+ " - " + food.getFoodTypeName() + '￥'+ food.getPrice());
                foodVO.setFoodName(food.getFoodName());
                foodVO.setFoodTypeName(food.getFoodTypeName());
                foodVO.setPrice(food.getPrice());
                foodVO.setCount(food.getCount());
                foodVO.setWeight(food.getWeight());
                foodVO.setUnit(food.getUnit());
                foodVO.setImgUrl(food.getImgUrl());
                foodVO.setOrigin(food.getOrigin());

                foodAllList.add(foodVO);
            }
        }
        map.put("foodAllList", foodAllList);
        return R.ok(map);
    }


    /**
     * 新增套餐
     */
    @SaCheckPermission("kitchen:setMeal:add")
    @Log(title = "套餐", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody KitchenSetMeal kitchenSetMeal) {
        if(kitchenSetMeal.getProvinceArray()!=null && kitchenSetMeal.getProvinceArray().length >= 2){
            kitchenSetMeal.setProvId(Integer.parseInt(kitchenSetMeal.getProvinceArray()[0]));
            kitchenSetMeal.setCityId(Integer.parseInt(kitchenSetMeal.getProvinceArray()[1]));
            kitchenSetMeal.setDistrictId(Integer.parseInt(kitchenSetMeal.getProvinceArray()[2]));
        }




        return toAjax(kitchenSetMealService.save(kitchenSetMeal));
    }

    /**
     * 修改套餐
     */
    @SaCheckPermission("kitchen:setMeal:edit")
    @Log(title = "套餐", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody KitchenSetMeal kitchenSetMeal) {
        if(kitchenSetMeal.getProvinceArray()!=null && kitchenSetMeal.getProvinceArray().length >= 2){
            kitchenSetMeal.setProvId(Integer.parseInt(kitchenSetMeal.getProvinceArray()[0]));
            kitchenSetMeal.setCityId(Integer.parseInt(kitchenSetMeal.getProvinceArray()[1]));
            kitchenSetMeal.setDistrictId(Integer.parseInt(kitchenSetMeal.getProvinceArray()[2]));
        }
        return toAjax(kitchenSetMealService.updateById(kitchenSetMeal));
    }

    /**
     * 删除套餐
     *
     * @param ids 主键串
     */
    @SaCheckPermission("kitchen:setMeal:remove")
    @Log(title = "套餐", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Integer[] ids) {
        return toAjax(kitchenSetMealService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
